import axios from 'axios'
import router from '@/router/router'
import store from '@/store/store';
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import {getToken} from '@/util/auth'
import {showError} from '@/util/util'

//返回其他状态码
axios.defaults.validateStatus = function (status) {
    return status >= 200 && status <= 500; // 默认的
};
//跨域请求，允许保存cookie
axios.defaults.withCredentials = true;

//NProgress Configuration
NProgress.configure({
    showSpinner: false
});

//HTTP Request拦截
axios.interceptors.request.use(config => {
    NProgress.start();
    config.headers['Content-Type'] = 'application/json';
    config.headers['Auth-Token'] = getToken();
    return config;
}, error => {
    return Promise.reject(error)
});

//HTTP Response拦截
axios.interceptors.response.use(res => {
    NProgress.done();
    const ok = res.data.ok || false;
    const status = res.data.code || 200;
    const message = res.data.message || '未知错误';
    //如果是401则跳转到登录页面
    if (status === 401) store.dispatch('FedLogOut').then(() => router.push({path: '/login'}));
    // 如果请求为 !ok 默认统一处理
    if (!ok) {
        showError(message);
        return Promise.reject(new Error(message));
    }
    return res.data;
}, error => {
    NProgress.done();
    showError('未知错误');
    return Promise.reject(new Error(error));
});

export default axios
